package com.mng.tableAPI;

import com.mng.dto.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class easyTest {
    public static void main(String[] args) throws Exception {
        // 1.创建流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 读取数据
        DataStreamSource<String> stringDS = env.readTextFile("src/main/resources/wc.txt");
        // 3.转化成POJO
        SingleOutputStreamOperator<SensorReading> sensorStream = stringDS.map(line -> {
            String[] strings = line.split(",");
            return new SensorReading(strings[0], Long.parseLong(strings[1]), Double.parseDouble(strings[2]));

        });
        // 4.创建表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 5.基于流创建一张表
        Table sensorTable = tableEnv.fromDataStream(sensorStream);

        // 6.调用table API进行转换操作
        Table result1 = sensorTable.select($("id"), $("temperaturre")) //Expression
                .where($("id").isEqual("sensor_1"));

        // 7.执行Sal
        tableEnv.createTemporaryView("sensor",sensorStream);
        String sql = "select id,temperaturre from sensor where id = 'sensor_1'";
        Table tableResult = tableEnv.sqlQuery(sql);

        // 8.输出
        tableEnv.toAppendStream(result1, Row.class).print("API");
        tableEnv.toAppendStream(tableResult, Row.class).print("sql");

        env.execute();

    }
}
